# -*- coding: utf-8 -*-
# filename: tcp_server.py
import re
import sys
import socket

# act_data_dict = {'x': '', 'y': ''}

def writeGps(data):
    with open("gps.data", "wb") as fs:
        fs.write(data)
    # with open("gps.data", "rb") as fs:
    #     GPS_DATA = fs.read()
    #     print GPS_DATA, type(GPS_DATA), len(GPS_DATA)
    #     gps = GPS_DATA.split(',')
    #     act_data_dict['x'] = gps[0]
    #     act_data_dict['y'] = gps[1]
    #     print act_data_dict


def tcp_server(port='8080'):
    firstConnectFlag = 0
    tcp_addr = ('0.0.0.0', int(port))
    # tcp_addr = ('172.28.171.87', int(port))
    tcps = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # tcps.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # tcps.settimeout(10)
    tcps.bind(tcp_addr)
    tcps.listen(2)
    client, addr = tcps.accept()
    firstConnectFlag = 1
    print addr
    while True:
        try:
            tcp_data = client.recv(255)
            print "OK: ", tcp_data, len(tcp_data)
            if firstConnectFlag :
                firstConnectFlag = 0
                client.send("OK")
            if len(tcp_data) == 0:
                client.close()
                client, addr = tcps.accept()
                firstConnectFlag = 1
            else:
                # client.send("OK")
                data = re.findall('^"[0-9]*.[0-9]*[N|S],[0-9]*.[0-9]*[E|W]"$', tcp_data)
                if len(data) > 0:
                    data = data[0][1:-1]
                    data = data.split(",")
                    gps = data[1][:-1] + ',' + data[0][:-1]
                    print gps
                    writeGps(gps)
        except Exception as e:
            print e
            client.close()
            client, addr = tcps.accept()
            firstConnectFlag = 1

if __name__ == '__main__':
    if len(sys.argv) == 2:
        print sys.argv[1]
        tcp_server(sys.argv[1])
    else:
        tcp_server()
